<template>
    <div class="app-container">

        <el-row :gutter="20" class="header">

            <el-input v-model="queryForm.query.name" style="width: 240px;margin: 0 10px; margin-bottom: 10px" clearable>
                <template #prepend>名称：</template>
            </el-input>
            <el-input v-model="queryForm.query.owner" style="width: 240px;margin: 0 10px; margin-bottom: 10px"
                clearable>
                <template #prepend>所有者：</template>
            </el-input>
            <el-input v-model="queryForm.query.startTime" type="date"
                style="width: 240px;margin: 0 10px; margin-bottom: 10px" format="YYYY-MM-DD" :suffix-icon="Calendar"
                clearable>
                <template #prepend>开始日期：</template>
            </el-input>
            <el-input v-model="queryForm.query.endTime" type="date"
                style="width: 240px;margin: 0 10px; margin-bottom: 10px" format="YYYY-MM-DD" :suffix-icon="Calendar"
                clearable>
                <template #prepend>结束日期：</template>
            </el-input>
            <el-button type="primary" :icon="Search" @click="initActiveList">查询</el-button>
            <br>
            <el-button type="success" :icon="DocumentAdd" @click="handleDialogValue()">新增</el-button>
            <el-popconfirm title="您确定批量" @confirm="handleDownload(2)">
                <template #reference>
                    <el-button type="danger" :disabled="delBtnStatus" :icon="Download">选择导出</el-button>
                </template>
            </el-popconfirm>
            <el-popconfirm title="您确定批量" @confirm="handleDownload(1)">
                <template #reference>
                    <el-button type="danger" :icon="Download">全量导出</el-button>
                </template>
            </el-popconfirm>

            <el-upload class="upload-demo" :action="getServerUrl() + '/crmActivity/importActivity'" :headers="headers"
                :on-success="handleAvatarSuccess" :before-upload="handleChange">
                <template #trigger>
                    <el-button type="danger" :icon="Upload">导入数据</el-button>
                </template>
            </el-upload>
        </el-row>

        <el-table v-if="tableData !== null" :data="tableData" stripe style="width: 100%"
            @selection-change="handleSelectionChange" @cell-click="handleCellClick" :cell-style="cellStyle">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="名称" align="center" />
            <el-table-column prop="owner" label="所有者" align="center" />
            <el-table-column prop="startDate" label="开始日期" align="center" />
            <el-table-column prop="endDate" label="结束日期" align="center" />

            <el-table-column prop="action" label="操作" width="200" fixed="right" align="center">
                <template v-slot="scope">

                    <el-button type="primary" :icon="Edit" @click="handleDialogValue(scope.row.id)" />
                    <el-popconfirm title="您确定要删除这条活动记录吗？" @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button type="danger" :icon="Delete" />
                        </template>
                    </el-popconfirm>

                </template>
            </el-table-column>
        </el-table>


        <el-pagination v-model:currentPage="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
            :page-sizes="[2, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 打开修改表格，传递id和标题名称，和初始化方法 -->
    <activeFrom v-model="dialogVisible" :dialogVisible="dialogVisible" :id="activeId" :dialogTitle="dialogTitle"
        @initUserList="initActiveList" />

    <activeDetail :id="detailId" v-model="detailVisible"  :dialogVisible="detailVisible"></activeDetail>
</template>

<script setup>
import { ref } from 'vue';
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus'
import { Search, Delete, DocumentAdd, Edit, Tools, Upload, Download } from '@element-plus/icons-vue'
import { useStore } from "@/store/piniaIndex"
import activeFrom from './components/activeFrom'
import activeDetail from './components/activeDetail';

const userStore = useStore();
//设置请求头
const headers = ref({
    Authorization: userStore.GET_TOKEN()
})

const queryForm = ref({
    query: {
        'name': '',
        'owner': '',
        'startTime': '',
        'endTime': ''
    },
    pageNum: 1,
    pageSize: 2
})

const tableData = ref([])
const total = ref(0)
const multipleSelection = ref([])
const delBtnStatus = ref(true)

//设置表单标题
const dialogTitle = ref("")
const activeId = ref("")
const detailId = ref("")
const dialogVisible = ref(false)
const detailVisible = ref(false)


//点击跳转
const handleCellClick = (row, column, cell, event) => {
    if (column.property === 'name') {
        detailId.value = row.id;
        detailVisible.value = true
    }
}
//设置样式
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
    if (column.property === 'name') {
        return {
            color: '#428BCA',
            'text-decoration': 'underline',
            cursor: 'pointer',
        };
    }
    return {};
};


// 初始化数据
const initActiveList = async () => {
    console.log(queryForm.value);
    const res = await requestUtil.post("/crmActivity/list", queryForm.value);
    tableData.value = res.data.data.tlist;
    total.value = res.data.data.total;
}
initActiveList();

// 勾选事件
const handleSelectionChange = (selection) => {
    multipleSelection.value = selection;
    delBtnStatus.value = selection.length == 0;
}

//下载按钮
const handleDownload = async (type) => {
    var ids = []

    if (type == 2) {
        if (!Boolean(multipleSelection.value)) {
            ElMessage({
                message: '请选择需要下载的数据',
                type: 'warning',
                plain: true,
            })
        } else {
            multipleSelection.value.forEach(row => {
                ids.push(row.id)
            })
            await requestUtil.downloadFile("crmActivity/fileDownload", ids)
        }

    } else {
        await requestUtil.downloadFile("crmActivity/fileDownload", ids)
    }

}



// 分页查询
const handleSizeChange = (pageSize) => {
    queryForm.value.pageNum = 1;
    queryForm.value.pageSize = pageSize;
    initActiveList();
}
// 改变事件
const handleCurrentChange = (pageNum) => {
    queryForm.value.pageNum = pageNum;
    initActiveList();
}

//检测文件
const handleChange = (uploadFile) => {
    console.log('触发上传', uploadFile);

    // 在此处检查文件类型（可以根据你的实际需求来检查文件类型） "application/vnd.ms-excel"

    const validFileTypes = ['application/vnd.ms-excel']; // 假设我们只允许上传 application/vnd.ms-excel文件

    if (!validFileTypes.includes(uploadFile.type)) {
        console.log('触发上传', uploadFile);
        ElMessage.warning(
            `文件类型不符合要求: ${uploadFile.type}`
        );
        return false; // 如果文件类型不符合要求，直接返回，避免继续上传
    }
    return true;
}

//上传事件
const handleAvatarSuccess = (res) => {
    if (res.code == 1) {
        ElMessage.success("执行成功！")
        initActiveList();
    } else {
        ElMessage.error(res.message);
    }
}

//添加
const handleDialogValue = (id) => {
    if (id) {
        activeId.value = id;
        console.log(' activeId.value = id;', activeId.value);

        dialogTitle.value = "活动修改"
    } else {
        activeId.value = "";
        dialogTitle.value = "活动添加"
    }
    dialogVisible.value = true
}

//删除
const handleDelete = async (id) => {
    var ids = []
    if (id) {
        ids.push(id)
    } else {
        ElMessage("请选择需要删除的数据！")
    }
    const res = await requestUtil.post("crmActivity/delete", ids)
    if (res.data.code == 1) {
        ElMessage({
            type: 'success',
            message: '执行成功!'
        })
        initActiveList();
    } else {
        ElMessage({
            type: 'error',
            message: res.data.message,
        })
    }
}

</script>

<style lang="scss" scoped>
.upload-demo {
    margin-left: 10px;
    /* 左侧间距 */
    margin-right: 10px;
    /* 右侧间距 */
}

.upload-button {
    margin-left: 10px;
    /* 左侧间距 */
    margin-right: 10px;
    /* 右侧间距 */
}
</style>